; void monocromatizar_inf_asm (
; 	unsigned char *src,
; 	unsigned char *dst,
; 	int h,
; 	int w,
; 	int src_row_size,
; 	int dst_row_size
; );

global monocromatizar_inf_asm

section .text

monocromatizar_inf_asm:
	;; TODO: Implementar
	push rbp
	mov rbp, rsp
	push rbx
	push r12
	push r13
	push r14
	push r15

	pxor xmm7, xmm7

	mov r15, rcx
	shr r15, 2					;divido por la cantidad de pixels simultaneos que proceso

	mov r13, rcx
	and r13, 3					;calculo el resto

	xor r12, r12
	cicloFilas:
		xor r11, r11
		cicloColumnas:
			lea r10, [rdi + r11*8]
			lea r10, [r10 + r11*4]
			movdqu xmm0, [r10]		;xmm0 = xx|xx|xx|xx|b4|g4|r4|b3|g3|r3|b2|g2|r2|b1|g1|r1

			movdqu xmm1, xmm0
			movdqu xmm2, xmm0

			psrldq xmm1, 1			;xmm1 = 00|xx|xx|xx|xx|b4|g4|r4|b3|g3|r3|b2|g2|r2|b1|g1
			psrldq xmm2, 2			;xmm2 = 00|00|xx|xx|xx|xx|b4|g4|r4|b3|g3|r3|b2|g2|r2|b1

			pmaxub xmm0, xmm1
			pmaxub xmm0, xmm2		;xmm0 = xx|xx|xx|xx|xx|xx|M4|xx|xx|M3|xx|xx|M2|xx|xx|M1

			pextrw eax, xmm0, 3		;eax = 00|00|xx|M3
			pextrw ebx, xmm0, 4		;ebx = 00|00|M4|xx
			mov ah, bh			;eax = 00|00|M4|M3
			shl eax, 16			;eax = M4|M3|00|00
			pextrw ebx, xmm0, 1		;ebx = 00|00|M2|xx
			mov ah, bh			;eax = M4|M3|M2|00
			pextrw ebx, xmm0, 0		;ebx = 00|00|xx|M1
			mov al, bl			;eax = M4|M3|M2|M1

			mov [rsi + r11 * 4], eax
		inc r11
		cmp r11, r15
		jl cicloColumnas

		cmp r13, 0
		je se_proceso_linea_completa
		shl r11, 1
		procesar_lo_que_queda:
			lea r10, [rdi + r11 * 2]
			lea r10, [r10 + r11]
			movd xmm0, [r10]		;xmm0 = xx|b1|g1|r1

			movq xmm1, xmm0
			movq xmm2, xmm0

			psrlq xmm1, 8			;xmm1 = 00|xx|b1|g1
			psrlq xmm2, 16			;xmm2 = 00|00|xx|b1

			pmaxub xmm0, xmm1
			pmaxub xmm0, xmm2		;xmm0 = xx|xx|xx|M1

			pextrw eax, xmm0, 0		;eax = 00|00|xx|M1

			mov [rsi + r11], al
		inc r11
		cmp r11, rcx
		jb procesar_lo_que_queda
		se_proceso_linea_completa:

		lea rdi, [rdi + r8 * 1]
		lea rsi, [rsi + r9 * 1]
	inc r12
	cmp r12, rdx
	jl cicloFilas

	pop r15
	pop r14
	pop r13
	pop r12
	pop rbx
	pop rbp
	ret
